import os

from django.core.paginator import Paginator
from django.shortcuts import render
from django.template import RequestContext, loader
from django.http import HttpResponse, JsonResponse
from .models import Student
from django.conf import settings
from functools import wraps


# Create your views here.
def index(request):
    template = loader.get_template('login.html')
    return HttpResponse(template.render())


def my_custom_decorator(view_func):
    @wraps(view_func)
    def wrapper_func(request, *args, **kwargs):
        # 在这里加入session的验证
        if request.session.get('userinfo') == None:
            template = loader.get_template('loginerror.html')
            return HttpResponse(template.render())
        response = view_func(request, *args, **kwargs)
        return response
    return wrapper_func


def checkpass(request):
    # 比较账号和密码，如果比较成功。跳转首页
    # 如果不成功是错误
    name = request.POST.get('title')
    password = request.POST.get('password')
    # 通过orm查询，判断有没有这个人，如果有，继续判断密码，如果没有直接提示错误
    is_exist = Student.objects.filter(name=name)
    if is_exist:
        if password == is_exist[0].password:
            # 如果密码也相等，让他登录
            # 登录成功，写入session，开启会话
            request.session['userinfo'] = {
                'name': name,
                'password': password,
                'img': is_exist[0].image
            }
            data = request.session['userinfo']
            return render(request, 'backend.html', data)
        else:
            template = loader.get_template('loginerror.html')
            return HttpResponse(template.render())
    else:
        template = loader.get_template('loginerror.html')
        return HttpResponse(template.render())



@my_custom_decorator
def student_list(request):
    template = loader.get_template('student_list.html')
    return HttpResponse(template.render())


def student_api(request):
    page = request.GET.get('page')
    limit = request.GET.get('limit')

    info = Student.objects.all().order_by('-id')
    data = []
    for x in info:
        temp = {'id': x.id, 'username': x.name, 'sex': x.gender, 'image': x.image, 'city': x.address, 'sign': x.sign}
        data.append(temp)

    p = Paginator(data, limit)  # limit 传递10
    counter = p.count
    res1 = p.page(page)  # page  传递 1
    res1 = res1.object_list
    res = {
        'code': 0,
        'count': counter,
        'data': res1,
        'msg': 'success'
    }
    return JsonResponse(data=res)


def student_add(request):
    template = loader.get_template('student_add.html')
    return HttpResponse(template.render())


def student_add_api(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    sex = request.POST.get('sex')
    city = request.POST.get('city')
    desc = request.POST.get('desc')
    img = request.POST.get('img')

    # 该写入数据库了
    res1 = Student.objects.create(
        name=username,
        password=password,
        gender=sex,
        address=city,
        sign=desc,
        image=img
                           )

    res = {
        'code': 0,
        'msg': '新增成功'
    }
    if res1 == None:
        res['code'] = 1
        res['msg'] = '新增失败'

    return JsonResponse(data=res)


def upload_img(request):
    file = request.FILES.get('file')
    # 文件存储的地址
    file_path = os.path.join(settings.BASE_DIR, 'static\\image\\' + file.name)
    # 文件url
    file_url = os.path.join('\\static\\image\\' + file.name)
    # 写入文件
    with open(file_path, 'wb') as uploaded_file:
        for chunk in file.chunks():
            uploaded_file.write(chunk)

    return JsonResponse(data={'filepath': file_url})


def student_del(request):
    id = request.POST.get('id')
    Student.objects.filter(id=id).delete()
    data = {
        'code': 0,
        'msg': '删除成功'
    }

    return JsonResponse(data=data)


def login_out(request):
    request.session.flush()
    data = {
        'code': 0,
        'msg': '退出成功'
    }
    return JsonResponse(data=data)


@my_custom_decorator
def student_edit(request):
    id = request.GET.get('id')
    # 有了id，可以查询这条数据
    info = Student.objects.filter(id=id)
    data = {
        'name': info[0].name,
        'gender': info[0].gender,
        'address': info[0].address,
        'sign': info[0].sign,
        'image': info[0].image,
        'password': info[0].password,
        'id': info[0].id
    }

    return render(request, 'student_edit.html', data)


@my_custom_decorator
def student_edit_api(request):
    info = request.POST.dict()
    res = Student.objects.filter(id=info['id']).update(**info)
    data = {
        'code': 0,
        'msg': '修改成功'
    }

    if res == None:
        data['code'] = 1
        data['msg'] = '修改失败'
    return JsonResponse(data=data)


def grade_add(request):
    id = request.GET.get('id')
    data = {
        'id': id
    }
    return render(request, 'grade_add.html', data)


def grade_add_api(request):
    info = request.POST.dict()
    print(info)
    # 接下来开始写数据库
    return JsonResponse(data={})